from fastapi import APIRouter, Query, Depends, HTTPException
from typing import Optional
from datetime import datetime
from app.modules.logs.models import OperationLogModel
from app.modules.logs.schemas import (
    OperationLogInfo, OperationLogListResponse, LogQueryParams, 
    LogStatistics, LogExportParams
)
from app.modules.logs.services import LogService
from app.core.responses import success_response, error_response
from app.core.exceptions import BusinessException
from app.core.dependencies import get_current_user
from app.modules.users.models import UserModel

router = APIRouter(
    prefix="/api/logs", 
    tags=["操作日志"]
)


@router.get("/", summary="获取操作日志列表", response_model=OperationLogListResponse)
async def get_log_list(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(50, ge=1, le=200, description="每页数量"),
    username: Optional[str] = Query(None, description="用户名"),
    module: Optional[str] = Query(None, description="操作模块"),
    action: Optional[str] = Query(None, description="操作动作"),
    method: Optional[str] = Query(None, description="HTTP方法"),
    ip: Optional[str] = Query(None, description="IP地址"),
    success: Optional[bool] = Query(None, description="是否成功"),
    status_code: Optional[int] = Query(None, description="状态码"),
    start_time: Optional[datetime] = Query(None, description="开始时间"),
    end_time: Optional[datetime] = Query(None, description="结束时间"),
    current_user: UserModel = Depends(get_current_user)
):
    """获取操作日志分页列表，支持多种查询条件"""
    query_params = LogQueryParams(
        username=username,
        module=module,
        action=action,
        method=method,
        ip=ip,
        success=success,
        status_code=status_code,
        start_time=start_time,
        end_time=end_time
    )
    
    total, items = await LogService.get_log_list(
        skip=(page - 1) * size, 
        limit=size,
        query_params=query_params
    )
    return success_response(data={"total": total, "items": items})


@router.get("/statistics", summary="获取日志统计信息", response_model=LogStatistics)
async def get_log_statistics(current_user: UserModel = Depends(get_current_user)):
    """获取日志统计信息，包括总数、成功数、错误数等"""
    statistics = await LogService.get_log_statistics()
    return success_response(data=statistics)


@router.get("/summary", summary="获取日志摘要信息")
async def get_log_summary(current_user: UserModel = Depends(get_current_user)):
    """获取日志摘要信息，包括今日、本周、本月统计"""
    summary = await LogService.get_log_summary()
    return success_response(data=summary)


@router.get("/recent", summary="获取最近日志")
async def get_recent_logs(
    hours: int = Query(24, ge=1, le=168, description="小时数"),
    current_user: UserModel = Depends(get_current_user)
):
    """获取最近N小时的操作日志"""
    logs = await LogService.get_recent_logs(hours)
    return success_response(data=logs)


@router.get("/error", summary="获取错误日志")
async def get_error_logs(
    limit: int = Query(50, ge=1, le=200, description="数量限制"),
    current_user: UserModel = Depends(get_current_user)
):
    """获取错误日志列表"""
    logs = await LogService.get_error_logs(limit)
    return success_response(data=logs)


@router.get("/user/{user_id}", summary="获取用户操作日志")
async def get_user_logs(
    user_id: int,
    limit: int = Query(50, ge=1, le=200, description="数量限制"),
    current_user: UserModel = Depends(get_current_user)
):
    """获取指定用户的操作日志"""
    logs = await LogService.get_user_logs(user_id, limit)
    return success_response(data=logs)


@router.get("/module/{module}", summary="获取模块操作日志")
async def get_module_logs(
    module: str,
    limit: int = Query(50, ge=1, le=200, description="数量限制"),
    current_user: UserModel = Depends(get_current_user)
):
    """获取指定模块的操作日志"""
    logs = await LogService.get_module_logs(module, limit)
    return success_response(data=logs)


@router.get("/{log_id}", summary="获取日志详情", response_model=OperationLogInfo)
async def get_log_detail(
    log_id: int,
    current_user: UserModel = Depends(get_current_user)
):
    """根据日志ID获取日志详情"""
    log = await LogService.get_log_by_id(log_id)
    if not log:
        raise BusinessException(message="日志不存在")
    return success_response(data=log)


@router.get("/time-range", summary="获取时间范围日志")
async def get_logs_by_time_range(
    start_time: datetime = Query(..., description="开始时间"),
    end_time: datetime = Query(..., description="结束时间"),
    current_user: UserModel = Depends(get_current_user)
):
    """获取指定时间范围的日志"""
    logs = await LogService.get_logs_by_time_range(start_time, end_time)
    return success_response(data=logs)


@router.post("/export", summary="导出日志")
async def export_logs(
    export_params: LogExportParams,
    current_user: UserModel = Depends(get_current_user)
):
    """导出日志数据"""
    export_data = await LogService.export_logs(export_params)
    return success_response(
        data={
            "format": export_params.format,
            "count": len(export_data),
            "data": export_data
        },
        message="日志导出成功"
    )


@router.delete("/old", summary="删除旧日志")
async def delete_old_logs(
    days: int = Query(30, ge=1, le=365, description="天数"),
    current_user: UserModel = Depends(get_current_user)
):
    """删除指定天数之前的日志"""
    deleted_count = await LogService.delete_old_logs(days)
    return success_response(
        data={"deleted_count": deleted_count},
        message=f"成功删除{deleted_count}条旧日志"
    )


@router.delete("/clear", summary="清空所有日志")
async def clear_all_logs(current_user: UserModel = Depends(get_current_user)):
    """清空所有日志（需要管理员权限）"""
    # 检查是否为超级管理员
    if not current_user.is_superuser:
        raise BusinessException(message="只有超级管理员才能清空所有日志")
    
    deleted_count = await LogService.clear_all_logs()
    return success_response(
        data={"deleted_count": deleted_count},
        message=f"成功清空{deleted_count}条日志"
    )


@router.get("/modules", summary="获取所有模块列表")
async def get_modules_list(current_user: UserModel = Depends(get_current_user)):
    """获取系统中所有操作模块的列表"""
    from tortoise.functions import Count
    modules_result = await OperationLogModel.all().annotate(
        count=Count('id')
    ).group_by('module').order_by('-count')
    
    modules = [
        {
            'module': item.module,
            'count': item.count
        } for item in modules_result
    ]
    return success_response(data=modules)


@router.get("/users", summary="获取活跃用户列表")
async def get_active_users_list(current_user: UserModel = Depends(get_current_user)):
    """获取系统中活跃用户的列表"""
    from tortoise.functions import Count
    users_result = await OperationLogModel.all().annotate(
        count=Count('id')
    ).group_by('username').order_by('-count').limit(50)
    
    users = [
        {
            'username': item.username,
            'count': item.count
        } for item in users_result
    ]
    return success_response(data=users) 